package com.mspbots.ticketai;

import com.mspbots.ticketai.graderule.GradeRuleInterceptor;
import com.mspbots.ticketai.model.TicketRule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * com.mspbots.core.ticketai.GradeRuleInterceptorRegistry
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2019/8/20
 */
@Service
public class GradeRuleInterceptorRegistry {

    private final List<GradeRuleInterceptorRegistration> registrations = new ArrayList<>();

    @Autowired
    public void registryInterceptor(Map<String, GradeRuleInterceptor> ruleInterceptorMap) {
        ruleInterceptorMap.forEach((key, value) -> this.addInterceptor(value, key));
    }

    public void addInterceptor(GradeRuleInterceptor interceptor, String interceptorName) {
        GradeRuleInterceptorRegistration registration = new GradeRuleInterceptorRegistration(interceptor, interceptorName);
        this.registrations.add(registration);
    }

    /**
     * Return all registered interceptors.
     */
    public List<GradeRuleInterceptorRegistration> getInterceptors(List<TicketRule> ticketRules) {
        return this.registrations.stream()
                .filter(registration ->
                        ticketRules.stream().map((Function<TicketRule, Object>) TicketRule::getName)
                                .collect(Collectors.toList()).contains(registration.getName()))
                .map(registration -> {
                    var ticketRule = ticketRules.stream()
                            .filter(rule -> rule.getName().equals(registration.getName()))
                            .findFirst();
                    return ticketRule.map(registration::prepare).orElse(null);
                })
                .collect(Collectors.toList());
    }
}
